package com.zcareu.logServ.controller;

import com.zcareu.logServ.entity.Filter;
import com.zcareu.logServ.entity.OwnedFilters;
import com.zcareu.logServ.repo.OwnedFiltersRepo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class OwnedFiltersController {
    @Autowired
    private OwnedFiltersRepo ownedFiltersRepo;

    @PostMapping(value = "/owned")
    public OwnedFilters save(String username, String filterName) {
        OwnedFilters ownedFilters = new OwnedFilters();
        ownedFilters.setUsername(username);
        ownedFilters.setFilterName(filterName);

        return ownedFiltersRepo.save(ownedFilters);
    }

    @GetMapping(value = "/owned/current")
    public List<Filter> show() {
        Subject subject = SecurityUtils.getSubject();

        return ownedFiltersRepo.findAllFilterNamesByOwner(subject.getPrincipal().toString());
    }

    @GetMapping(value = "/owned")
    public Page<OwnedFilters> index(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        return ownedFiltersRepo.findAll(PageRequest.of(page, size));
    }
}
